<template>
  <div class="depInfo">
    <div class="header">
      <div class="avatar">
        <a-avatar :size="100" :src="avatarUrl" />
      </div>
      <div class="empInfo">
        <div>
          {{ name
          }}<span
            style="display: inline-block;line-height:22px;width:60px;height:22px;text-align:center;background:rgb(255,223,223);border-radius:11px;border:1px solid rgba(255,0,0,0.42);color:rgb(255,124,124);font-size: 14px;margin-left: 10px"
          >
            {{ getEmployeeStatus(status, formalType) }}
          </span>
        </div>
        <div
          style="display: inline-block;width: 166px;height: 30px;line-height:30px;text-align: center;background:rgba(252,175,79,0.12);border-radius:15px;font-size: 14px;font-weight: 500"
        >
          手机号 <span style="color: rgba(106, 101, 246,1)">{{ phone }}</span>
        </div>
        <div
          v-if="joinDate"
          style="margin-left:10px;display: inline-block;width: 166px;height: 30px;line-height:30px;text-align: center;background:rgba(252,175,79,0.12);border-radius:15px;font-size: 14px;font-weight: 500"
        >
          入职时间
          <span style="color: rgba(106, 101, 246,1)">{{ joinDate | formatDate }}</span>
        </div>
      </div>
    </div>
    <div class="container">
      <a-form :form="form" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }">
        <a-form-item :colon="false" label="岗位">
          <a-input v-decorator="['positionName', { initialValue: empChanges.positionName }]" disabled />
        </a-form-item>

        <a-form-item :colon="false" label="变更为">
          <a-tree-select v-decorator="['currentPositionIdList']" multiple :tree-data="positionOptions" allow-clear />
        </a-form-item>

        <a-form-item :colon="false" label="部门">
          <a-input v-decorator="['depName', { initialValue: empChanges.depName }]" disabled />
        </a-form-item>

        <a-form-item :colon="false" label="变更为">
          <a-tree-select v-decorator="['currentDepIdList']" multiple :tree-data="departmentOptions" allow-clear />
        </a-form-item>

        <a-form-item :colon="false" label="职级">
          <a-input v-decorator="['level', { initialValue: empChanges.level }]" disabled />
        </a-form-item>

        <a-form-item :colon="false" label="变更为">
          <a-input-number v-decorator="['currentLevel']" />
        </a-form-item>

        <a-form-item :colon="false" label="主管">
          <a-input v-decorator="['supervisor', { initialValue: empChanges.supervisor }]" disabled />
        </a-form-item>

        <a-form-item :colon="false" label="变更为">
          <a-input v-decorator="['currentSupervisor']" />
        </a-form-item>

        <a-form-item :colon="false" label="管理形式">
          <a-select v-decorator="['managerForm', { initialValue: empChanges.managerForm }]" disabled :options="managerModusOptions" />
        </a-form-item>

        <a-form-item :colon="false" label="变更为">
          <a-select v-decorator="['currentManagerForm']" :options="managerModusOptions" />
        </a-form-item>

        <a-form-item :colon="false" label="工作城市">
          <area-component :disabled="true" :region.sync="empChanges.workCityId" :only-province="true" />
        </a-form-item>

        <a-form-item :colon="false" label="变更为">
          <area-component :region.sync="currentWorkCityId" :only-province="true" />
        </a-form-item>

        <a-form-item :colon="false" style="display: block" label="调岗时间" required>
          <a-date-picker
            v-decorator="[
              'adjustmentDate',
              {
                rules: [{ required: true, message: '请输入' }],
                initialValue: empChanges.adjustmentDate
              }
            ]"
            type="date"
          />
        </a-form-item>

        <a-form-item :colon="false" style="display: block" label="调岗原因">
          <a-input v-decorator="['adjustmentReason']" type="textarea" />
        </a-form-item>

        <a-form-item :colon="false" label="附件">
          <a-upload
            :before-upload="beforeUpload"
            :remove="handleFileRemove"
            class="upload-ele"
            accept=".doc,.docx,.xls,.xlsx,.pdf,.zip,.rar"
            multiple
            :file-list="fileList"
          >
            <a-button style="height: 33px"> <a-icon type="upload" /> 选择文件</a-button>
            <a-button
              type="primary"
              :loading="uploading"
              style="margin-left: 25px;height: 33px;"
              :disabled="fileList.length === 0 || uploading"
              @click.stop="uploadFile"
              >{{ uploading ? "正在上传" : "开始上传" }}</a-button
            >
            <div>
              文件格式为 DOC/DOCX/XLS/XLSX/PDF/ZIP/RAR，大小在5MB内 ，数量在5个以内
            </div>
          </a-upload>
        </a-form-item>
      </a-form>

      <div class="button-area">
        <a-button type="button" class="mr20" @click="cancel">取消</a-button>
        <a-button class="submit-btn" type="primary" @click="transferJob">
          提交
        </a-button>
      </div>
    </div>
  </div>
</template>

<script>
import { transferJob, getTransferJobInfo } from "@/api/staff/empChanges";
import { findEmpInfoTitle } from "@/api/staff/staff";
import { getDepartmentInTree } from "@/api/department/department";
import { getPositionInTree } from "@/api/department/position";
import { uploadAttachmentFiles, saveSubjectAttachment } from "@/api/file/file";
import AreaComponent from "./component/area";

export default {
  name: "Detail",
  filters: {
    formatDate
  },
  components: { AreaComponent },
  data() {
    return {
      form: this.$form.createForm(this),
      companyId: "",
      name: "",
      status: "",
      formalType: "",
      phone: "",
      joinDate: "",
      employInfoId: this.$route.query.empInfoId,
      employInfo: "",
      currentWorkCityId: "",
      empIdCardPicture: "",
      avatarUrl: "",
      empChanges: {},
      fileList: [],
      uploading: false,
      positionOptions: [],
      departmentOptions: [],
      managerModusOptions: [
        { label: "请选择", value: "" },
        { label: "总部", value: 0 },
        { label: "分城市", value: 1 },
        { label: "其它", value: 2 }
      ] // 管理形式
    };
  },
  created() {
    this.companyId = this.$store.state.hr.companyId;
  },
  mounted() {
    this.initData();
  },
  methods: {
    alertResultMessage(result) {
      let type = "success";
      if (result.code !== 200) {
        type = "error";
      }

      this.$notification[type]({
        message: result.msg
      });
    },
    cancel: function() {
      this.$router.go(-1);
    },
    transferJob: function(e) {
      e.preventDefault();
      if (this.fileList.length > 0 && this.empIdCardPicture !== null) {
        this.$notification["error"]({
          message: "文件未上传"
        });
        return;
      }
      this.form.validateFields((err, values) => {
        if (!err) {
          var that = this;
          that.$confirm({
            title: "调岗",
            content: "确定调岗?",
            onOk() {
              values.empIds = [that.employInfoId];
              values.companyId = that.companyId;
              values.adjustmentAttachment = that.empIdCardPicture;
              values.currentWorkCityId = that.currentWorkCityId;

              transferJob(values).then(res => {
                that.alertResultMessage(res);
                if (res.code === 200) {
                  that.cancel();
                }
              });
            },
            onCancel() {}
          });
        }
      });
    },
    handleFileRemove(file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
      if (newFileList.length === 0) {
        this.empIdCardPicture = null;
        return;
      }
      this.uploadFile();
    },
    beforeUpload(file) {
      if (file.size > 5242880) {
        this.$notification["warning"]({
          message: "文件最大为5MB"
        });
        return false;
      }
      if (this.fileList.length > 4) {
        this.$notification["warning"]({
          message: "最多上传5个文件"
        });
        return false;
      }
      this.fileList = [...this.fileList, file];
      return false;
    },

    uploadFile() {
      this.uploading = true;
      const { fileList } = this;
      const formData = new FormData();
      fileList.forEach(file => {
        formData.append("files", file);
      });
      uploadAttachmentFiles(formData).then(res => {
        if (res.code !== 200) {
          this.$notification["warning"]({
            message: "处理失败"
          });
        }
        this.uploading = false;
        const fileIds = [];
        for (const obj of res.data) {
          fileIds.push(obj.id);
        }
        const params = {
          fileIds: fileIds,
          subjectId: this.employInfoId,
          subjectType: "hr_emp_job_adjust"
        };
        saveSubjectAttachment(params).then(res => {
          this.alertResultMessage(res);
          if (res.code === 200) {
            this.empIdCardPicture = params.subjectId;
          }
        });
      });
    },
    tree(array, childKey, onlyLastChild) {
      if (array === null || array.length < 1) {
        return [];
      }
      array.map((item, index) => {
        item["value"] = item.id;
        item["key"] = item.id;
        item["label"] = item.name;
        item["children"] = item[childKey];

        if (item.children) {
          item["disabled"] = onlyLastChild;
          this.tree(item.children, childKey, onlyLastChild);
        }
      });
      return array;
    },
    getEmployeeStatus(status, formalType) {
      if (status === 1) {
        return "待入职";
      } else if (status === 2) {
        if (formalType === 1) {
          return "适用期";
        } else {
          return "在职";
        }
      } else if (status === 4) {
        return "离职";
      }
      return "在职";
    },
    initData() {
      findEmpInfoTitle({
        id: this.employInfoId,
        companyId: this.companyId
      }).then(res => {
        const data = res.data;
        this.name = data.name;
        this.joinDate = data.joinDate;
        this.phone = data.phone;
        this.avatarUrl = data.empPhoto;
        this.formalType = data.formalType;
        this.status = data.status;
      });

      getTransferJobInfo({
        id: this.employInfoId,
        companyId: this.companyId
      }).then(res => {
        this.empChanges = res.data;
      });
      getPositionInTree({ companyId: this.companyId }).then(res => {
        this.positionOptions = this.tree(res.data, "positionChildList", true);
      });
      getDepartmentInTree({ companyId: this.companyId }).then(res => {
        this.departmentOptions = this.tree(res.data[0].depChildList, "depChildList");
      });
    }
  }
};

function formatDate(value) {
  if (isNaN(value) || value === "") {
    return "";
  }
  const date = new Date(value);
  const Y = date.getFullYear();
  let m = date.getMonth() + 1;
  let d = date.getDate();
  let H = date.getHours();
  let i = date.getMinutes();
  let s = date.getSeconds();
  if (m < 10) {
    m = "0" + m;
  }
  if (d < 10) {
    d = "0" + d;
  }
  if (H < 10) {
    H = "0" + H;
  }
  if (i < 10) {
    i = "0" + i;
  }
  if (s < 10) {
    s = "0" + s;
  }
  const t = Y + "-" + m + "-" + d;
  return t;
}
</script>

<style lang="scss" scoped>
.depInfo {
  padding: 10px 15% 0 15%;
}

.depInfo > div {
  border-radius: 12px;
}

.header {
  width: 100%;
  background: white;
  padding: 40px 0;
}

.avatar {
  margin-left: 50px;
  display: inline-block;
  position: relative;

  .ant-avatar {
    width: 100px;
    height: 100px;
    border: 1px solid rgba(232, 232, 232, 1);

    > img {
      width: 100%;
      height: 100%;
    }
  }
}

.empInfo {
  display: inline-block;
  line-height: 50px;
  vertical-align: top;
  margin-left: 40px;
}

.header-button-group {
  width: 100%;
  text-align: right;
  padding-right: 32px;
  margin-bottom: 10px;
}

.container {
  width: 100%;
  background: white;
  border-radius: 12px;
  padding-top: 80px;
  margin-bottom: 58px;
  margin-top: 25px;
}

.ant-row.ant-form-item {
  width: 45%;
  display: inline-block;
}

.ant-calendar-picker {
  width: 100%;
}

>>> input.ant-input {
  height: 36px;
}

.ant-btn {
  min-width: 90px;
  height: 38.5px;
}
.ant-btn-primary:not([disabled="disabled"]) {
  background-color: var(--primary);
  color: white;
  border-color: #f5f5f5;
}

.button-area {
  width: 100%;
  height: 58px;
  line-height: 58px;
  border-top: 1px solid #e5e5e5;
  margin-top: 40px;
  text-align: right;
  padding-right: 40px;
}

.button-area .ant-btn {
  width: 106px;
}
.submit-btn {
  color: white;
}
.submit-btn:hover {
  color: white;
  border: none;
}
.submit-btn:focus {
  outline: none;
  border: none;
}
</style>
